#!/usr/bin/env python
# encoding: utf-8
'''
@author: 王震
@license: 四川凡狼科技有限公司
@contact: 2668985108@qq.com
@file: user.py
@time: 2021/10/17 4:08 下午
@desc:
'''

from app.public.sqlMethods import existence
from app.msg.resp import response_json, response_list_json
from app.msg.tips import tipsText, tips
from app.model.user.user import User
from app.public.tool import create_key
from app.serialize.user import UserObj
from werkzeug.security import generate_password_hash, check_password_hash
from app.public.sqlMethods import create_token
from main import db
from flask import request
from app.public.sqlMethods import t, auto_commit_db


def user_register(data):
    token = request.headers['token']
    user_token_obj = t.loads(token)
    obj = {
        'telephone': '',
        "password": ""
    }
    if existence(obj=data, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    with auto_commit_db():
        _user = User.query.filter_by(id=user_token_obj['id']).first()
        if _user.telephone != 'admin':
            return response_json(code=tips['only_admin_create'], msg=tipsText['only_admin_create'])
        res = User.query.filter_by(telephone=data['telephone']).count()
        if res:
            return response_json(code=tips['exists'], msg=tipsText['exists'])
        user = User()
        for key in data:
            setattr(user, key, data[key]) if hasattr(user, key) and data[key] else None
        user.id = create_key()
        user.password = generate_password_hash(data['password'])
        db.session.add(user)
    return response_json()


def login(data):
    obj = {
        'telephone': '',
        "password": ""
    }
    if existence(obj=data, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    with auto_commit_db():
        res = User.query.filter_by(telephone=data['telephone']).first()
        if not res:
            return response_json(code=tips['exist'], msg=tipsText['exist'])
        if not check_password_hash(res.password, data['password']):
            return response_json(code=tips['wrong'], msg=tipsText['wrong'])
        token = create_token(obj=res)
    # 返回token
    return response_json(data=token)


def get_list(page_number, page_size):
    with auto_commit_db():
        pages = User.query.paginate(int(page_number), int(page_size), False)
        item = pages.items
        user_obj = UserObj(many=True)
        data = user_obj.dump(item)
    return response_list_json(data=data, page_number=pages.page, page_size=pages.pages)


def user_info():
    token = request.headers['token']
    res = t.loads(token)
    with auto_commit_db():
        res = User.query.filter_by(id=res['id']).first()
        user_obj = UserObj()
        data = user_obj.dump(res)
    return response_json(data=data)
